<?php
namespace Common\Controller;
use Think\Controller;
use Home\Controller\PublicController;
class CommonController extends Controller {
	protected $AppSecret = '536887f16f2fe2a8d8d9c88c5441af6e';
	protected $AppID = 'wx57b559484ac7a0c1';
    protected $assess_token = '';
    protected $config = [];
 	public function _initialize(){




            if($_GET['router']){
                cookie('order_id',$_GET['order_id']);

                     cookie('my_cnt',9);

//                    cookie('status',1);
//                    cookie('arr',$arr);

            }else{
                //if(!cookie('status')) {
                   // cookie('arr', null);
                //}
                cookie('my_cnt',1);
            }




        //dump(cookie('status'));die();

		$list=M("Config")->select();
		foreach ($list as $k=>$v){
			$list[$v['key']]=$v['value'];
		}
		$this->config=$list;
		//获取assess_token
			 $assess_token = S('assess_token');
			if(empty($assess_token)){
				$http =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->AppID."&secret=".$this->AppSecret;
				
				$result = $this->curl_get($http);
				
				$assess_token = $result['access_token'];
				S('assess_token',$assess_token);
				S('assess_time',time());
			}
			$assess_time = S('assess_time');
			if(time() - $assess_time >= 7200){
				$http =  "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$this->AppID."&secret=".$this->AppSecret;
				$result = $this->curl_get($http);
				
				$assess_token = $result['access_token'];
				S('assess_token',$assess_token);
				S('assess_time',time());
			} 
		
			$this->assess_token = $assess_token; 
			//unset($_SESSION);
			//获取OPENID
			//如果数据库有数据
			/*if(empty($_SESSION['openid'])){
				$list = $this->weiXinLogin();
				if(!empty($list['openid'])){
					setcookie('openids1',$list['openid'],time()+3600);
					$_SESSION['openid'] = $list['openid'];
					$_SESSION['access_token'] = $list['access_token'];
					$_SESSION['expires_in'] = $list['expires_in'];
					$_SESSION['openid_time'] = time();
					$_SESSION['refresh_token'] = $list['refresh_token'];
				}else{
					echo '网络异常！';exit();
				}
				
			}*/
		
     }
	
	//使用curl的GET请求数据  返回数组
	protected function curl_get($http){
		//初始化
			$ch = curl_init();
			//设置选项，包括URL
			curl_setopt($ch, CURLOPT_URL, $http);
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_HEADER, 0);
			//执行并获取HTML文档内容
			$output = curl_exec($ch);
			//释放curl句柄
			curl_close($ch);
			//打印获得的数据
			$result = json_decode($output,true);
			return $result;
	}
	
	public function userAuthorize($a) {
        $redirect_uri = urlencode('http://ydp.mylei.cn');
		$get_token_url = "http://open.weixin.qq.com/connect/oauth2/authorize?appid=".$this->AppID."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=liujinming#wechat_redirect";
		// dump($get_token_url);die;
		header("Location:".$get_token_url);


    }
    /**
     * 微信登录
     */
    public function weiXinLogin($aaa = "") {

         $appid = $this->AppID;
         $secret = $this->AppSecret;
        if (!isset($_GET["code"])) {
             $this->userAuthorize($aaa);
         }
         $code = $_GET["code"];

		 // dump($code);
         // 获取access_token、openid等其他信息
         $get_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
         $res = file_get_contents($get_token_url);
         // 解析返回结果
		 //dump($res);die;
         $json_obj = json_decode($res, true);
		  // dump($json_obj);

		  // dump($_SESSION);
		  // return json_decode($res, true);
         if (!empty($json_obj['access_token'])) {
             // 根据openid和access_token查询用户信息
			 // dump($json_obj);
             return $json_obj;
         }else {

             return -1001;
         }
    }
	/**
	*获取用户信息  $field 查询字段   str
	*/
	protected function get_user($field){
		$where['openid'] = $_SESSION['openid'];
		$member = M('Member')->Field($field)->where($where)->find();
		return $member;
	}
	
	/**
	 * 图片处理
	 */
	public function upload($file){
		///判断是否是图片类型
		switch($file['type'])
		{
			case 'image/jpeg': $ext = 'jpg'; break;
			case 'image/gif': $ext = 'gif'; break;
			case 'image/png': $ext = 'png'; break;
			case 'image/tiff': $ext = 'tif'; break;
			case 'image/bmp': $ext = 'bmp'; break;
			default: $ext = ''; break;
		}
		if (empty($ext)){
			$this -> error('不支持的图片格式');
		}
		$upload = new \Think\Upload();// 实例化上传类
		$upload ->maxSize   =  9999999 ;// 设置附件上传大小
		$upload ->exts      =  array('jpg', 'gif', 'png', 'jpeg','bmp');// 设置附件上传类型
		$upload ->savePath  =  '/'; // 设置附件上传目录    // 上传单个文件
		$upload ->saveName  =  rand(1000,9999).time();
		$info   =   $upload->uploadOne($file);
		if(!$info) {// 上传错误提示错误信息
			$this ->error($upload->getError());
		}else{
			$pic=$info['savepath'].$info['savename'];
			$url='/Uploads'.ltrim($pic,".");
			return $url;
		}
	}
	
}


